package com.atguigu.srb.core.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.atguigu.srb.core.mapper.DictMapper;
import com.atguigu.srb.core.pojo.dto.ExcelDictDto;
import lombok.NoArgsConstructor;

import java.util.ArrayList;
import java.util.List;

@NoArgsConstructor
public class ExcelDictDtoListener extends AnalysisEventListener<ExcelDictDto> {

    private DictMapper dictMapper;

    public ExcelDictDtoListener(DictMapper dictMapper) {
        this.dictMapper = dictMapper;
    }

    // 每隔5条批量插入数据 生产环境一般3000条
    private static final int BATCH_COUNT = 10;

    private List<ExcelDictDto> list = new ArrayList<>();


    @Override
    public void invoke(ExcelDictDto data, AnalysisContext context) {
        list.add(data);
        if (list.size() >= BATCH_COUNT){
            saveData();
            list.clear();
        }
    }

    private void saveData() {
        dictMapper.insertBatch(list);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        // 最后剩余的数据不足 BATCH_COUNT 时候添加最后数据
        saveData();
    }
}
